package com.tools.scanner.ui.history.fragment

import android.graphics.Rect
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.tools.scanner.BaseFragment
import com.tools.scanner.R
import com.tools.scanner.database.PdfInfo
import com.tools.scanner.database.QrHistory
import com.tools.scanner.database.ScannerDatabase
import com.tools.scanner.databinding.FragmentCreateHistoryBinding
import com.tools.scanner.databinding.FragmentDocumentHistoryBinding
import com.tools.scanner.databinding.FragmentScannerHistoryBinding
import com.tools.scanner.databinding.RecyclerDocumentHistoryItemBinding
import com.tools.scanner.ui.history.QrHistoryAdapter
import com.tools.scanner.ui.pdf.PreviewPdfActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class DocumentHistoryFragment : BaseHistoryFragment() {

    private lateinit var mBinding: FragmentDocumentHistoryBinding

    private var mSearchContent = ""

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mBinding = FragmentDocumentHistoryBinding.inflate(layoutInflater)
        return mBinding.root
    }

    private val mAdapter = DocumentHistoryAdapter {
        PreviewPdfActivity.actionStart(requireContext(), it)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mBinding.refreshLayout.setOnRefreshListener {
            search(mSearchContent)
        }

        mBinding.recyclerView.layoutManager = LinearLayoutManager(requireContext())
        mBinding.recyclerView.addItemDecoration(object : RecyclerView.ItemDecoration() {
            private val margin = resources.getDimension(R.dimen.dp_10).toInt()
            override fun getItemOffsets(outRect: Rect, itemPosition: Int, parent: RecyclerView) {
                if (itemPosition != 0) {
                    outRect.top = margin
                }

                outRect.left = margin
                outRect.right = margin
            }
        })
        mBinding.recyclerView.adapter = mAdapter
    }

    override fun onResume() {
        super.onResume()
        search(mSearchContent)
    }

    override fun search(content: String) {
        mSearchContent = content
        val query = if (content.isEmpty()) "" else "%$content%"

        mBinding.refreshLayout.isRefreshing = true
        lifecycleScope.launch(Dispatchers.IO) {
            val historyList = ScannerDatabase.get().searchPdfInfo(query)
            withContext(Dispatchers.Main) {
                mBinding.refreshLayout.isRefreshing = false
                mAdapter.refresh(historyList)
            }
        }
    }

}

class DocumentHistoryAdapter(private val onClick: (pdfInfo: PdfInfo) -> Unit) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private val pdfInfoList = mutableListOf<PdfInfo>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val layoutInflater = LayoutInflater.from(parent.context)
        val binding = RecyclerDocumentHistoryItemBinding.inflate(layoutInflater, parent, false)
        return DocumentViewHolder(binding, onClick)
    }

    override fun getItemCount(): Int {
        return pdfInfoList.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is DocumentViewHolder) {
            holder.refresh(pdfInfoList[position])
        }
    }

    fun refresh(list: List<PdfInfo>) {
        pdfInfoList.clear()
        pdfInfoList.addAll(list)
        notifyDataSetChanged()
    }

    fun deleteItem(qrHistory: QrHistory) {
        for (index in 0 until pdfInfoList.size) {
            if (pdfInfoList[index].id == qrHistory.id) {
                deleteItem(index)
                return
            }
        }
    }

    fun deleteItem(index: Int) {
        pdfInfoList.removeAt(index)
        notifyItemRemoved(index)
    }

    private class DocumentViewHolder(
        private val mBinding: RecyclerDocumentHistoryItemBinding,
        private val onClick: (pdfInfo: PdfInfo) -> Unit
    ) : RecyclerView.ViewHolder(mBinding.root) {

        private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())

        init {
            mBinding.root.setOnClickListener {
                val pdfInfo = it.tag
                if (pdfInfo is PdfInfo) {
                    onClick(pdfInfo)
                }
            }
        }

        fun refresh(pdfInfo: PdfInfo) {
            mBinding.root.tag = pdfInfo
            mBinding.tvName.text = pdfInfo.name
            mBinding.tvDate.text = dateFormat.format(Date(pdfInfo.ctime))
            mBinding.image.let {
                Glide.with(it).load(pdfInfo.firstPhoto).into(it)
            }
        }
    }

}










